﻿using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace WRCControl
{
    public sealed class RTNPullBottomPanel : Control
    {
        private ScrollViewer _containerScrollViewer;

        private EventRegistrationTokenTable<RoutedEventHandler> m_ScrollBottomTokenTable = null;

        public event RoutedEventHandler ScrollBottom
        {
            add { return EventRegistrationTokenTable<RoutedEventHandler>.GetOrCreateEventRegistrationTokenTable(ref m_ScrollBottomTokenTable).AddEventHandler(value); }
            remove { EventRegistrationTokenTable<RoutedEventHandler>.GetOrCreateEventRegistrationTokenTable(ref m_ScrollBottomTokenTable).RemoveEventHandler(value); }
        }

        public RTNPullBottomPanel()
        {
            this.Loaded += RTNPullBottomPanel_Loaded;
        }

        void RTNPullBottomPanel_Loaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= RTNPullBottomPanel_Loaded;
            RegisteScrollListener();
        }

        private void RegisteScrollListener()
        {
            GridView gridView = this.Parent.Descendents().OfType<GridView>().FirstOrDefault();
            ListView listView = this.Parent.Descendents().OfType<ListView>().FirstOrDefault();
            if (gridView != null && gridView.Visibility == Visibility.Visible)
            {
                _containerScrollViewer = gridView.Descendents().OfType<ScrollViewer>().FirstOrDefault();
            }
            else if (listView != null && listView.Visibility == Visibility.Visible)
            {
                _containerScrollViewer = listView.Descendents().OfType<ScrollViewer>().FirstOrDefault();
            }
            if (_containerScrollViewer != null)
            {
                _containerScrollViewer.ViewChanged += OnViewChanged;
            }
        }

        void OnViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
        {
            //TODO 这个地方可做延伸动画
            //Debug.WriteLine("HorizontalOffset---->" + _containerScrollViewer.HorizontalOffset);
            //Debug.WriteLine("ScrollableWidth---->" + this._containerScrollViewer.ScrollableWidth);
            if (_containerScrollViewer.HorizontalOffset > this._containerScrollViewer.ScrollableWidth - 0.1)
            {
                //Debug.WriteLine("event calling--->");
                OnScrollBottom();
            }
        }

        internal void OnScrollBottom()
        {
            RoutedEventHandler temp = EventRegistrationTokenTable<RoutedEventHandler>.GetOrCreateEventRegistrationTokenTable(ref m_ScrollBottomTokenTable).InvocationList;
            if (temp != null)
            {
                temp(this, new RoutedEventArgs());
            }
        }
    }
}
